<template>
  <el-form label-width="180px" style="margin: 20px;">
    <el-form-item label="Files Upload">
      <uploader
        ref="uploader"
        :options="options"
        :file-status-text="statusText"
        :show-success-files="true"
        @file-complete="fileComplete"
        @file-download="fileDownload"
        @file-delete="fileDelete"
      />
    </el-form-item>
  </el-form>
</template>

<script>
import Uploader from '@/components/SimpleUploader'

export default {
  name: 'upload',
  components: {
    Uploader
  },
  data() {
    return {
      options: {
        target: process.env.VUE_APP_BASE_API + '/oss/file/upload',
        testChunks: false,
        chunkSize: 10 * 1024 * 1024,
        query: {},
        generateUniqueIdentifier: () => {
          return this.guid()
        }
      },
      statusText: {
        success: '100%',
        error: '失败',
        uploading: '上传中',
        paused: '暂停中',
        waiting: '等待中'
      }
    }
  },
  methods: {
    fileComplete(file) {
      // 当分块上传后，调用服务端合并
      if (file.chunks.length > 1) {
        this.mergeFile(file.uniqueIdentifier, file.chunks.length, file.name)
      }
    },
    mergeFile(id, totalChunks, filename) {
      this.$api.oss.file.mergeChunks({ id, totalChunks, filename })
    },
    fileDownload(file) {
      this.$api.oss.file.download({ id: file.uniqueIdentifier, name: file.name })
    },
    fileDelete(file) {
      this.$api.oss.file.remove({ id: file.uniqueIdentifier, name: file.name })
    },
    guid() {
      return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0
        const v = c === 'x' ? r : (r & 0x3 | 0x8)
        return v.toString(16)
      })
    }
  }
}

</script>
